 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=85 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:39 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Time execution speed
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='measure,optimisation,optimization,performance,stopwatch,speed,time,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Time execution speed</div>

<div class='main-body'>
 
<br>Here is an example of a utility <tt>Stopwatch</tt> class which can
provide timings for any section of code.
<p>For measuring the relative execution times of alternate implementations,
consider turning off the HotSpot compiler, using 
<tt><a href="http://java.sun.com/javase/6/docs/technotes/tools/windows/java.html#nonstandard" title="Non-standard options for java.">java -Xint</a></tt>.
This will ensure a uniform environment for the entire duration of a program.
See the <a href="TopicActionb30e-2.html">Copy an array</a> topic for an illustration.
<br>
<PRE>

<span class='comment'>/** Time the execution of any block of code. */</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> Stopwatch {

  <span class='comment'>/**
  * An example of the use of this class to
  * time the execution of String manipulation code.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main (String... arguments) {
    Stopwatch stopwatch = <span class='keyword'>new</span> Stopwatch();

    stopwatch.start();

    <span class='comment'>//do stuff
</span>    StringBuilder messageOne = <span class='keyword'>new</span> StringBuilder();
    <span class='keyword'>int</span> numIterations = <span class='literal'>5000</span>;
    <span class='keyword'>for</span>(<span class='keyword'>int</span> idx=<span class='literal'>0</span>; idx &lt; numIterations; ++idx){
      messageOne.append(<span class='literal'>"blah"</span>);
    }

    stopwatch.stop();
    <span class='comment'>//Note that there is no need to call a method to get the duration,
</span>    <span class='comment'>//since toString is automatic here
</span>    System.out.println(<span class='literal'>"The reading for StringBuilder is: "</span> + stopwatch);

    <span class='comment'>//reuse the same stopwatch to measure an alternative implementation
</span>    <span class='comment'>//Note that there is no need to call a reset method.
</span>    stopwatch.start();

    <span class='comment'>//do stuff again
</span>    String messageTwo = <span class='keyword'>null</span>;
    <span class='keyword'>for</span>(<span class='keyword'>int</span> idx=<span class='literal'>0</span>; idx &lt; numIterations; ++idx){
      messageTwo = messageTwo + <span class='literal'>"blah"</span>;
    }

    stopwatch.stop();
    <span class='comment'>//perform a numeric comparsion
</span>    <span class='keyword'>if</span> ( stopwatch.toValue() &gt; <span class='literal'>5</span> ) {
      System.out.println(<span class='literal'>"The reading is high: "</span> + stopwatch);
    }
    <span class='keyword'>else</span> {
      System.out.println(<span class='literal'>"The reading is low: "</span> + stopwatch);
    }
  }

  <span class='comment'>/**
  * Start the stopwatch.
  *
  * @throws IllegalStateException if the stopwatch is already running.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>void</span> start(){
    <span class='keyword'>if</span> ( fIsRunning ) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalStateException(<span class='literal'>"Must stop before calling start again."</span>);
    }
    <span class='comment'>//reset both start and stop
</span>    fStart = System.currentTimeMillis();
    fStop = <span class='literal'>0</span>;
    fIsRunning = <span class='keyword'>true</span>;
    fHasBeenUsedOnce = <span class='keyword'>true</span>;
  }

  <span class='comment'>/**
  * Stop the stopwatch.
  *
  * @throws IllegalStateException if the stopwatch is not already running.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>void</span> stop() {
    <span class='keyword'>if</span> ( !fIsRunning ) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalStateException(<span class='literal'>"Cannot stop if not currently running."</span>);
    }
    fStop = System.currentTimeMillis();
    fIsRunning = <span class='keyword'>false</span>;
  }

  <span class='comment'>/**
  * Express the "reading" on the stopwatch.
  *
  * @throws IllegalStateException if the Stopwatch has never been used,
  * or if the stopwatch is still running.
  */</span>
  <span class='keyword'>public</span> String toString() {
    validateIsReadable();
    StringBuilder result = <span class='keyword'>new</span> StringBuilder();
    result.append(fStop - fStart);
    result.append(<span class='literal'>" ms"</span>);
    <span class='keyword'>return</span> result.toString();
  }

  <span class='comment'>/**
  * Express the "reading" on the stopwatch as a numeric type.
  *
  * @throws IllegalStateException if the Stopwatch has never been used,
  * or if the stopwatch is still running.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>long</span> toValue() {
    validateIsReadable();
    <span class='keyword'>return</span> fStop - fStart;
  }

  <span class='comment'>// PRIVATE ////
</span>  <span class='keyword'>private</span> <span class='keyword'>long</span> fStart;
  <span class='keyword'>private</span> <span class='keyword'>long</span> fStop;

  <span class='keyword'>private</span> <span class='keyword'>boolean</span> fIsRunning;
  <span class='keyword'>private</span> <span class='keyword'>boolean</span> fHasBeenUsedOnce;

  <span class='comment'>/**
  * Throws IllegalStateException if the watch has never been started,
  * or if the watch is still running.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>void</span> validateIsReadable() {
    <span class='keyword'>if</span> ( fIsRunning ) {
      String message = <span class='literal'>"Cannot read a stopwatch which is still running."</span>;
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalStateException(message);
    }
    <span class='keyword'>if</span> ( !fHasBeenUsedOnce ) {
      String message = <span class='literal'>"Cannot read a stopwatch which has never been started."</span>;
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalStateException(message);
    }
  }
}
 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicActionb30e-2.html?Id=3'>Copy an array </a> <br>
 
  
  <a href='TopicAction851d-2.html?Id=4'>String concatenation does not scale</a> <br>
 
  
  <a href='TopicAction8240-2.html?Id=36'>Measure application performance</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='85'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=85 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:40 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
